#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "task.h"

typedef void(*func_t)();

#define N 3
func_t tasks[N] = {NULL};

void LoadTask()
{
    tasks[0] = PrintLog;
    tasks[1] = Download;
    tasks[2] = MysqlDataSync;
}

void HandlerTask()
{
    for (int i = 0; i < N; i++)
    {
        tasks[i]();
    }
}

void DoOtherThing()
{
    HandlerTask();
}

void ChildRun()
{
        int cnt = 5;
        while(cnt)
        {
            printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
            cnt--;
            sleep(1);
        }
}

int main()
{
    printf("I am father process, pid: %d, ppid: %d\n", getpid(), getppid());
    pid_t id = fork(); // 创建子进程
    if (id == 0)
    {
        // child
        ChildRun(); // 子进程运行 5 秒
        printf("Child quit!\n");
        exit(1); // 子进程退出，设置退出码为 1
    }
    LoadTask();
    // father
    // 非阻塞轮询
    while(1)
    {
        int status; // 获得子进程退出信息
        pid_t rid = waitpid(id, &status, WNOHANG);
        if (rid > 0)
        {
            // 等待成功
            
            if (WIFEXITED(status) != 0)
            {
                // 子进程正常退出，打印退出信息
                printf("Child quit normal, exit_code: %d\n", WEXITSTATUS(status));
            }
            else
            {
                // 子进程异常退出
                printf("Child quit unnormal!\n");
            }
            // 等待成功
            printf("Wait sucess, rid:%d\n", rid);
            break;
        }
        else if (rid == 0)
        {
            // 检测成功，子进程还未退出
            
            usleep(1000);
            printf("Child is running, father check next time!\n");
            DoOtherThing();
        }
        else
        {
            // 等待失败
            printf("Wait failed!\n");
            break;
        }
    } 
    sleep(2);
    printf("Father quit\n");
    // 父进程退出
    return 0;
}
